<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="70%">
      <el-form
        :model="inputForm"
        ref="inputForm"
        v-loading="loading"
        :class="method==='view'?'readonly':''"
        :disabled="method==='view'"
        label-width="120px">

        <!-- 基础信息 -->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="名称" prop="planName">
              <el-input v-model="inputForm.planName" placeholder="请填写名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="类型" prop="planType">
              <el-select v-model="inputForm.planType" placeholder="请选择" style="width: 100%;" @change="handleTypeChange">
                <el-option label="巡检计划" value="巡检计划"/>
                <el-option label="巡更计划" value="巡更计划"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="分配方式" prop="assigneeType">
              <el-select v-model="inputForm.assigneeType" placeholder="请选择" style="width: 100%;" disabled>
                <el-option
                  v-for="item in $dictUtils.getDictList('inspection_assignment_type')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="启用状态" prop="status">
              <el-select v-model="inputForm.status" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in $dictUtils.getDictList('enabled')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="巡查部门" prop="assigneeDepartment">
              <el-select v-model="inputForm.assigneeDepartment" multiple collapse-tags placeholder="请选择巡更部门"
                         style="width: 100%;" disabled>
                <el-option
                  v-for="item in officeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="巡查人员" prop="assigneeTo">
              <!-- 编辑/新增模式 -->
              <el-select
                v-if="method !== 'view'"
                v-model="inputForm.assigneeTo"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请选择巡查人员"
                :remote-method="getAssigneeList"
                style="width: 100%;">
                <el-option
                  v-for="item in assigneeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
              <!-- 查看模式 -->
              <span v-else>{{ inputForm.assigneeTo.join(', ') }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 巡更时间 -->
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="巡查时间" prop="scheduledTime">
              <div style="display: flex; align-items: flex-start; flex-wrap: wrap;">
                <el-time-picker
                  v-model="selectedTime"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  placeholder="选择时间"
                  @change="addTimePoint"
                  style="margin-right: 20px; margin-bottom: 10px; width: 180px;"
                  :disabled="method === 'view'"
                />
                <div style="flex: 1; display: flex; flex-wrap: wrap; align-items: center; min-height: 40px;">
                  <el-tag
                    v-for="(time, index) in timePoints"
                    :key="index"
                    closable
                    :disable-transitions="false"
                    @close="removeTimePoint(index)"
                    style="margin-right: 10px; margin-bottom: 10px;">
                    {{ time }}
                  </el-tag>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 巡更点位设置 -->
        <el-divider>巡查点位设置</el-divider>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="巡查楼层" prop="floorIds">
              <div style="display: flex; align-items: flex-start; flex-wrap: wrap;">
                <el-select
                  v-model="selectedFloor"
                  placeholder="选择楼层"
                  style="margin-right: 20px; margin-bottom: 10px; width: 180px;"
                  :disabled="method === 'view'"
                  @change="addFloorPoint"
                >
                  <el-option
                    v-for="item in floorList"
                    :key="item.id"
                    :label="item.showName"
                    :value="item.id"/>
                </el-select>
                <div style="flex: 1; display: flex; flex-wrap: wrap; align-items: center; min-height: 40px;">
                  <el-tag
                    v-for="(floor, index) in selectedFloors"
                    :key="index"
                    closable
                    :disable-transitions="false"
                    @close="removeFloorPoint(index)"
                    style="margin-right: 10px; margin-bottom: 10px;">
                    {{ getFloorName(floor) }}
                  </el-tag>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      title: '',
      method: '',
      visible: false,
      loading: false,
      selectedTime: null,
      timePoints: [],
      selectedFloor: null,
      selectedFloors: [],
      inputForm: {
        id: '',
        planName: '',
        planType: '巡更计划',
        assigneeType: '自动',
        status: '启用',
        assigneeTo: [],
        assigneeDepartment: [],
        floorNames: '',
        userName: '',
        officeName: '',
        bookshelfNames: '',
        scheduledTime: '',
        inspectionPoints: [{ floorIds: '' }]
      },
      officeList: [],
      userList: [],
      floorList: [],
      assigneeList: [],
      pointRows: 1
    }
  },
  methods: {
    init (method, id) {
      this.method = method
      this.inputForm.id = id
      this.visible = true
      this.loading = false
      this.selectedFloors = []
      this.timePoints = []

      this.getOfficeList().then(() => {
        return this.getAssigneeList()
      }).then(() => {
        this.getFloorList()
        if (method === 'add') {
          this.title = `新建巡查计划`
        } else if (method === 'edit' || method === 'view') {
          this.title = method === 'edit' ? '修改巡查计划' : '查看巡查计划'
          this.loading = true
          this.$http({
            url: `/inspection/inspectionPlan/queryById?id=${id}`,
            method: 'get'
          }).then(({data}) => {
            let planData = data.inspectionPlan || {}

            if (planData.assigneeDepartment && typeof planData.assigneeDepartment === 'string') {
              planData.assigneeDepartment = planData.assigneeDepartment.split(',')
            }

            if (planData.assigneeTo && typeof planData.assigneeTo === 'string') {
              const assigneeIds = planData.assigneeTo.split(',')
              if (this.method === 'view') {
                // 转换为姓名
                planData.assigneeTo = assigneeIds.map(id => {
                  const user = this.assigneeList.find(u => u.id === id)
                  return user ? user.name : id
                })
              } else {
                planData.assigneeTo = assigneeIds
              }
            }

            if (planData.scheduledTime) {
              this.timePoints = planData.scheduledTime.split(',')
              planData.scheduledTime = planData.scheduledTime
            }

            this.inputForm = Object.assign({}, this.inputForm, planData)
            this.loading = false
          })
        }
      })
    },
    doSubmit () {
      this.$refs['inputForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          let submitData = JSON.parse(JSON.stringify(this.inputForm))
          submitData.assigneeDepartment = submitData.assigneeDepartment.join(',')
          submitData.assigneeTo = submitData.assigneeTo.join(',')
          submitData.scheduledTime = this.timePoints.join(',')
          submitData.routeId = [...new Set(this.selectedFloors)].join(',')
          submitData.floorIds = submitData.routeId

          this.$http({
            url: `/inspection/inspectionPlan/save`,
            method: 'post',
            data: submitData
          }).then(({data}) => {
            if (data && data.success) {
              this.visible = false
              this.$message.success(data.msg)
              this.$emit('refreshDataList')
            }
            this.loading = false
          })
        }
      })
    },
    getOfficeList () {
      return this.$http({
        url: '/sys/office/list',
        method: 'get'
      }).then(({data}) => {
        if (data && data.success) {
          this.officeList = data.list
          const deptName = this.inputForm.planType === '巡检计划' ? '计检部' : '安保部'
          const defaultDept = this.officeList.find(office => office.name === deptName)
          if (defaultDept) {
            this.inputForm.assigneeDepartment = [defaultDept.id]
            this.inputForm.officeName = defaultDept.name
          }
        }
      })
    },
    handleTypeChange (val) {
      this.inputForm.planType = val
      this.inputForm.assigneeDepartment = []
      this.inputForm.assigneeTo = []
      this.assigneeList = []
      this.getOfficeList().then(() => this.getAssigneeList())
    },
    getAssigneeList (query = '') {
      const officeId = this.inputForm.assigneeDepartment && this.inputForm.assigneeDepartment[0]
      if (!officeId) return Promise.resolve()
      return this.$http({
        url: '/sys/user/listByOfficeId',
        method: 'get',
        params: { officeId, name: query }
      }).then(({data}) => {
        if (data && data.success) {
          this.assigneeList = data.data.map(item => ({
            id: item.id,
            name: item.name
          }))
        }
      })
    },
    getFloorList () {
      this.$http({
        url: '/smis/floor/jfFloor/list',
        method: 'get'
      }).then(({data}) => {
        if (data && data.success && Array.isArray(data.page.list)) {
          this.floorList = data.page.list.map(item => ({
            id: item.id,
            showName: item.showName || item.name
          }))
        }
      })
    },
    addTimePoint (val) {
      if (val && !this.timePoints.includes(val)) {
        this.timePoints.push(val)
        this.$message.success(`已添加时间点: ${val}`)
      }
      this.selectedTime = null
    },
    removeTimePoint (index) {
      this.timePoints.splice(index, 1)
    },
    addFloorPoint (val) {
      if (val && !this.selectedFloors.includes(val)) {
        this.selectedFloors.push(val)
        this.$message.success(`已添加楼层`)
      }
      this.selectedFloor = null
    },
    removeFloorPoint (index) {
      this.selectedFloors.splice(index, 1)
    },
    getFloorName (floorId) {
      const floor = this.floorList.find(item => item.id === floorId)
      return floor ? floor.showName : floorId
    }
  }
}
</script>
